<?php 
namespace Material\Controller;
use Think\Controller;
/**
 * 文件控制器
 * @author Haiqin
 *
 */
class FileController extends Controller{
	protected $app; //针对应用
	protected $qiniu; //七牛接口对象
	protected $extArr;
	protected $m;
	
	function _initialize() {
		$this->app = array('appid'=>C('DEFAULT_APPID'));
		$config = C('QINIU_CONFIG');
		
		$this->qiniu = new \Think\Upload\Driver\Qiniu($config);
		
		//定义允许上传的文件扩展名
		$this->extArr = array(
				'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
				'flash' => array('swf', 'flv'),
				'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
				'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt','pptx', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
		);
		
		$this->m = D('MaterialFiles');
	}
	
	/**
	 * 上传图片到七牛空间
	 */
	public function upload(){
		if(!empty($_FILES)){

			$max_size = 100*1024*1024; //不能上传大于100M的文件
			//原文件名
			$file_name = $_FILES['imgFile']['name'];
			//服务器上临时文件名
			$tmp_name = $_FILES['imgFile']['tmp_name'];
			//文件大小
			$file_size = $_FILES['imgFile']['size'];
			//检查文件名
			if (!$file_name) {
				echo '{"error":1,"message":"请选择文件。"}';//上传异常，输出异常信息
				return;
			}
			//检查文件大小
			if ($file_size > $max_size) {
				echo '{"error":1,"message":"上传文件大小超过限制。"}';//上传异常，输出异常信息
				return;
			}
				
			//获得文件扩展名
			$temp_arr = explode(".", $file_name);
			$file_ext = array_pop($temp_arr);
			$file_ext = trim($file_ext);
			$file_ext = strtolower($file_ext);
			//检查扩展名
			if (in_array($file_ext, $this->extArr['file']) === false) {
				echo '{"error":1,"message":"上传文件扩展名是不允许的扩展名。\n只允许' . implode(",", $this->extArr['file']) . '格式。"}';//上传异常，输出异常信息
				return;
			}
				
			$str = new \Org\Util\String();
				
			$file['savename'] = C('SERVER_KEY').$str->keyGen().'.'.$file_ext;
			$file['savepath'] = '';
			$file['tmp_name'] = $tmp_name;
				
				
			//上传到七牛服务器
			if($this->qiniu->save($file)){
				//存储数据组装
				$data['appid'] = $this->app['appid'];
				$data['name'] = $file_name;
				$data['key'] = $file['savename'];
				$data['url'] = $this->qiniu->downLink($file['savename']);
				$data['create_time'] = date('Y-m-d H:i:s');
				$data['size'] = $file_size;
				if(1){
					$fileID = $this->m->add($data);
					if($fileID){
						//$path = '/material/file/download/aid/'.base64_encode($data['appid']).'/id/'.$fileID;
						echo '{"error":0,"url":"'.$data['url'].'","file_id":"'.$fileID.'","file_path":"'.$data['url'].'","file_name":"'.$data['name'].'"}';
						die();
					}else{
						echo '{"error":1,"message":"数据存储失败。"}';//上传异常，输出异常信息
						die();
					}
				}else{
					echo '{"error":1,"message":"存储数据组装异常。"}';//上传异常，输出异常信息
					die();
				}
			}else{
				echo '{"error":1,"message":"服务器上传失败，请检查您的七牛配置。"}';//上传异常，输出异常信息
				die();
			}
				
		}
	}
	
	public function del(){
		$id = array_unique((array)I('ids',0));
		if ( empty($id) ) {
			$this->error('请选择要操作的数据!');
		}
		$map = array($this->m->getPk() => array('in', $id));
		$lists = $this->m->where($map)->select();
		if($this->m->where($map)->delete()){ //删除本地数据库中的row
			foreach($lists as $vo){
				$this->qiniu->del($vo['key']); //删除七牛远程图片
			}
			$this->success('删除成功');
		} else {
			$this->error('删除失败！');
		}
	}
	
	/*
	 * 跨域不成功
	 */
	public function download(){
		if(!$_GET['id']){
			$this->error("文件不存在");
		}else{//如果要加登录条件，这里可以自己加
			$dl = $this->m;
			$map['file_id'] = array('eq',$_GET['id']);
			$list=$dl->where($map)->find();
			dump($list);
			if ($list == false) {//文件不存在，可以跳转到其它页面
				header('HTTP/1.0 404 Not Found');
				header('Location: .');
			} else {
				/*
				if(!file_exists($list['url'])){
					$this->error('没有该文件文件');
					return ;
				}
				*/
				/*
				$handle = fopen (”http://www.xxx.com/”, “rb”);
				$contents = “”;
				do {
					$data = fread($handle, 8192);
					if (strlen($data) == 0) {
						break;
					}
					$contents .= $data;
				} while(true);
				fclose ($handle);
				echo $contents;
				*/
				
				$fp = fopen($list['url'], "rb");
				$file_size = $list['size'];
				$file_name = iconv("utf-8","gb2312",$list['name']);
				//下载文件需要用到的头
				
				Header("Content-type: application/octet-stream"); 
				Header("Accept-Ranges: bytes"); 
				Header("Accept-Length:".$file_size); 
				Header("Content-Disposition: attachment; filename=".$file_name); 
				$buffer=1024; 
				$file_count=0; 
				//向浏览器返回数据 
				while(!feof($fp) && $file_count<$file_size){ 
					$file_con=fread($fp,$buffer); 
					$file_count+=$buffer; 
					echo $file_con; 
				} 
				fclose($fp); 
				
			}
		}
	}
	
	
	
	public function getfile(){
		$data = $this->m->where('file_id = '.$_GET['id'])->find();
		$this->ajaxReturn($data,'数据获取成功',1);
	}
}
?>